﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Xml.Linq;
using Kaio.Web.UI;
using Kaio.Web.UI.Attributes;
using MvcForum.Net.Bussiness;

namespace MvcForum.Net.Controllers
{
    [ValidateIpAddress(Order = 1)]
    [IsNotModified(Order = 2)]
    [RemoveHtmlWhiteSpace(Order = 3)]
    /*[Compression(Order = 4)]*/
    /*[OutputCache(Duration = 20, Order = 5)]*/
    /*[HandleError(View = "Error")]*/
    public class ForumController : BaseController
    {
        //
        // GET: /Forum/


        #region Forum List

        public ActionResult Index(int? id, string title, int? page)
        {


            List<Forum> data;

            if (id.HasValue && id.Value > 0)
            {

                if (!ForumContext.Configuration.AllowGuestReadForums && !ForumContext.AllowReadForums)
                {
                    ViewBag.ActiveUrl = new ForumUrl { Title = ForumContext.GetText(LanguageSection.MESSAGES, "PAGE_NAME") };

                    ViewBag.ShowLogin = true;
                    ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.AccessDenied);

                    return View("Message");

                }


                ViewBag.ForumId = id.Value;

                data = new List<Forum>();

                var f = ForumRepo.Info(id.Value);
                data.Add(f);


                bool _IsShowTopic;

                ViewBag.IsShowTopic = _IsShowTopic = f.ParentId > 0;

                int _pageIndex = page.HasValue ? page.Value : 1;

                bool _isMod = ForumContext.IsModerated(f.ForumId);


                ViewBag.ActiveUrl = new ForumUrl
                                        {
                                            Title = f.ForumName,
                                            Url = ForumContext.ForumLink(f.ForumId, f.ForumName, _pageIndex),
                                            ShortUrl = ForumContext.GetAbsoluteUrl(ForumUrls.FIND_FORUM, f.ForumId),
                                            Keywords = f.Keywords,
                                            Description = f.Description,
                                            ForumId = f.ForumId,
                                            RssLink = ForumContext.Feed(f.ForumId, f.ForumName)
                                        };

                ViewBag.NavAddress = ForumRepo.BuildForumUrls(f.ForumId);

                if (_IsShowTopic)
                {
                    int _totalRows;

                    var _topics = TopicRepo.List(f.ForumId, _isMod, _pageIndex, f.TopicsPerPage, ((SortOrderBy)f.SortOrder).ToString(), ((SortDirection)f.SortDirection).ToString(), out _totalRows);

                    ViewBag.Topics = new ViewModelResult
                    {
                        Forum = f,
                        IsMod = _isMod,
                        List = _topics,
                        Type = ResultType.Topics,
                        ButtonPageRenderPosition = (ButtonPageRenderPosition)ForumContext.Configuration.ButtonPageRenderPosition,

                        PageRender = ForumContext.PageRender(ForumContext.ForumLink(f.ForumId, f.ForumName, "{0}"), _pageIndex, f.TopicsPerPage, _totalRows)
                    };

                }




            }
            else // Home Page
            {
                data = ForumRepo.InHomePage(0);

                ViewBag.ActiveUrl = new ForumUrl
                                        {
                                            IsHomePage = true,
                                            Title = ForumContext.Configuration.ForumName,
                                            Url = ForumContext.Configuration.AbsoluteUrl,
                                            Keywords = ForumContext.Configuration.Keywords,
                                            Description = ForumContext.Configuration.Description

                                        };

                ViewBag.Statistics = StatisticRepo.Info(ForumContext.Configuration.PastMinutes);

                ViewBag.MaxUserOnline = StatisticRepo.MaxUserOnline();

                ViewBag.UsersOnline = UsersRepo.OnlineList();

                ViewBag.ForumId = 0;

            }


            if (Request.IsAjaxRequest() || Request.QueryString["ajax"] == "1")
            {
                return PartialView("Forum", data);
            }

            return View("Forum", data);
        }


        #endregion


        #region Thread List

        public ActionResult Thread(int id, int? page, string title)
        {


            if (!ForumContext.Configuration.AllowGuestReadTopics && !ForumContext.AllowReadTopics)
            {
                ViewBag.ActiveUrl = new ForumUrl
                {
                    Title = ForumContext.GetText(LanguageSection.MESSAGES, "PAGE_NAME")
                };

                ViewBag.ShowLogin = true;
                ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.AccessDenied);

                return View("Message");

                //return RedirectToRoute("Message", Messages.AccessDenied);
            }



            var _t = TopicRepo.Detail(id);
            bool _isMod = _t != null && ForumContext.IsModerated(_t.ForumId);

            if (_t == null || (!_t.IsApproved && !_isMod))
            {
                ViewBag.ActiveUrl = new ForumUrl
                {
                    Title = ForumContext.GetText(LanguageSection.MESSAGES, "PAGE_NAME")
                };

                ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.PostNotFound);
                return View("Message");
            }




            List<Like> _likes;
            var f = ForumRepo.Info(_t.ForumId);
            int _pageIndex = page.HasValue ? page.Value : 1;

            int _totalRows;


            var _posts = TopicRepo.Thread(_isMod, id, _pageIndex, f.PostsPerPage, out _totalRows, out _likes);

            var _currentUrl = new ForumUrl
                                    {
                                        Title = _t.TopicName,
                                        Url = ForumContext.ThreadLink(_t.TopicId, _t.TopicName, _pageIndex),
                                        ParentUrl = ForumContext.GetAbsoluteUrl(ForumUrls.FIND_FORUM, _t.ForumId),
                                        Keywords = !string.IsNullOrWhiteSpace(_t.Tags) ? _t.Tags : _t.TopicName,
                                        Description = _t.Message.HtmlToPlainText().TruncateAtWord(145),
                                        ForumId = _t.ForumId,
                                        TopicId = _t.TopicId,
                                        Created = _t.Created,
                                        RssLink = ForumContext.Feed(f.ForumId, f.ForumName)

                                    };


            //var _navAddress = ForumRepo.BuildForumUrls(_t.XForumId.HasValue ? _t.XForumId.Value : _t.ForumId);
            var _navAddress = ForumRepo.BuildForumUrls(_t.ForumId);

            _navAddress.Add(_currentUrl);

            ViewBag.NavAddress = _navAddress;
            ViewBag.ActiveUrl = _currentUrl;

            int _pageSize = ForumContext.Logined
                                ? ForumContext.UserInfo.Permissions.SearchResultsPerPage
                                : ForumContext.Configuration.PageSize;


            var _result = new ViewModelResult
                              {
                                  Forum = f,
                                  Topic = _t,
                                  List = _posts,
                                  OtherList = _likes,
                                  Type = ResultType.Posts,
                                  IsMod = _isMod,
                                  ButtonPageRenderPosition = (ButtonPageRenderPosition)ForumContext.Configuration.ButtonPageRenderPosition,
                                  PageRender =
                                      ForumContext.PageRender(
                                          ForumContext.ThreadLink(_t.TopicId, _t.TopicName, "{0}"), _pageIndex,
                                          _pageSize, _totalRows)
                              };

            if (Request.IsAjaxRequest() || Request.QueryString["ajax"] == "1")
                return PartialView("Thread", _result);

            return View(_result);
        }


        #endregion


        #region FindPost


        public ActionResult FindPost(int id)
        {
            return Go(id);
        }

        public ActionResult Go(int id)
        {

            int _totalRows;
            string _returnUrl;

            string _act = Request.QueryString["do"];

            if (!string.IsNullOrWhiteSpace(_act) && (_act.ToUpper() != "NEXT" && _act.ToUpper() != "PREV"))
            {
                _act = "";
            }

            var _post = TopicRepo.FindPost(id, _act, out _totalRows);


            if (_post != null)
            {
                if (!string.IsNullOrEmpty(_post.RemoteUrl))
                {
                    _returnUrl = _post.RemoteUrl;
                }
                else
                {

                    var _f = ForumRepo.Info(_post.ForumId);

                    int _ppp = _f.PostsPerPage;

                    var _pageIndex = (int)Math.Ceiling((double)(_totalRows + 1) / _ppp);


                    _returnUrl =
                        ForumContext.ThreadLink(_post.ReplyTo.HasValue ? _post.ReplyTo.Value : _post.TopicId, _post.TopicName,
                                                (_pageIndex > 1) ? _pageIndex : 1) +
                        string.Format("?target=post{0}", _post.TopicId);

                }
            }
            else
            {

                _returnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.PostNotFound);
            }

            if (Request.IsAjaxRequest())
            {

                if (!string.IsNullOrWhiteSpace(_act) && _post == null)
                {
                    return JavaScript(string.Format("$.KoolBox.alert('{0}')", ForumContext.GetText(LanguageSection.MESSAGES, Messages.FindNextOrPrevNoResults)));
                }

                return JavaScript(string.Format("$.MvcForum.jump('{0}');", _returnUrl));

            }
            return Redirect(_returnUrl);
        }

        #endregion


        #region Find Forum

        public ActionResult GoF(int Id)
        {
            return FindForum(Id);
        }

        public ActionResult FindForum(int id)
        {

            var _f = ForumRepo.Info(id);

            if (_f != null)
            {
                if (!string.IsNullOrEmpty(_f.RemoteUrl))
                {
                    return Redirect(_f.RemoteUrl);
                }

                return Redirect(ForumContext.ForumLink(_f.ForumId, _f.ForumName));
            }
            return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.ForumNotFound));
        }
        #endregion


        #region Like

        [ValidateAuthentication]
        public ActionResult Like()
        {
            int _id = int.Parse(Request["Id"]);


            var t = TopicRepo.Detail(_id);

            LikeRepo.Save(_id, ForumContext.UserInfo.UserId, t.UserId, 1); // 1: Save, 0: Remove

            if (t.UserId != ForumContext.UserInfo.UserId)
                NotificationRepo.Save((short)CommandType.Like, ForumContext.UserInfo.UserId, t.UserId, null, _id, ForumContext.GetAbsoluteUrl(ForumUrls.FIND_POST, _id));

            var l = LikeRepo.List(_id, 1, 1);

            var model = new ViewModelResult
                            {
                                Topic = t,
                                OtherList = l,
                                IsMod = ForumContext.IsModerated(t.ForumId)
                            };


            if (Request.IsAjaxRequest())
            {
                return PartialView("_Post", model);
            }
            return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.FIND_POST, _id));


        }

        #endregion




        #region Command
        [RequiredAuthentication]
        public ActionResult Cmd()
        {
            int _id = int.Parse(Request["Id"]);

            var _cmd = (CommandType)int.Parse(Request["act"]);


            Forum _f = null;
            Topic _t = null;

            switch (_cmd)
            {
                case CommandType.UnLockForum:
                case CommandType.LockForum:

                    if (ForumContext.IsAdmin)
                    {
                        ForumRepo.ToggleLock(_id);
                        return JavaScript(string.Format("$.MvcForum.jump(window.location.href)"));
                        //                        return Redirect(ForumContext.ForumLink(_id, "", _pageIndex) + "?ajax=1");
                    }


                    break;

                case CommandType.LockTopic:
                case CommandType.UnLockTopic:
                    _t = TopicRepo.Detail(_id);
                    _f = ForumRepo.Info(_t.ForumId);
                    if (ForumContext.AllowAccess(_cmd, _f, _t))
                    {
                        TopicRepo.ToggleLock(_id);
                        return JavaScript(string.Format("$.MvcForum.jump(window.location.href)"));
                    }

                    break;

                case CommandType.Delete:

                    if (ForumContext.Logined)
                    {
                        _t = TopicRepo.Detail(_id);
                        _f = ForumRepo.Info(_t.ForumId);
                        if (ForumContext.AllowAccess(_cmd, _f, _t))
                        {
                            TopicRepo.Del(_id, _f.ForumId);

                            if (_t.ReplyTo > 0)
                            {
                                return JavaScript(string.Format("$('#post{0}').fadeOut()", _id)); //Redirect(ForumContext.ThreadLink(t.ReplyTo, t.TopicName, _pageIndex) + "?ajax=1");
                            }

                            return
                                JavaScript(
                                    string.Format("$.MvcForum.jump('{0}')", ForumContext.GetAbsoluteUrl(ForumUrls.FIND_FORUM, _t.ForumId)));

                        }

                    }

                    break;


            }

            return JavaScript(string.Format("$.MvcForum.jump('{0}')", ForumContext.GetAbsoluteUrl(ForumUrls.MEMBERS, Messages.ModerateAccessDenied)));

            //throw new Exception(ForumContext.GetText(LanguageSection.MESSAGES, Messages.ModerateAccessDenied));

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateAuthentication]
        [ValidateAntiModelInjection("f")]
        public ActionResult Cmd(FormCollection form)
        {


            string _ids = form["Ids"];
            int _fid = int.Parse(form["f"]);
            DateTime? _expires;
            DateTime _dateTime;

            var _cmd = (ModerateCommandType)int.Parse(form["act"]);

            var _msg = Msg.Create();
            Moderator _mod = ForumContext.Mod(_fid);


            if (ForumContext.AllowAccess(_cmd, _fid))
            {

                switch (_cmd)
                {
                    case ModerateCommandType.Approve:
                        TopicRepo.Mod_Queue(_ids, _fid, true, ForumContext.IsSuperMod || _mod.ApproveTopics, ForumContext.IsSuperMod || _mod.ApprovePosts);
                        break;
                    case ModerateCommandType.Queue:

                        TopicRepo.Mod_Queue(_ids, _fid, false, ForumContext.IsSuperMod || _mod.QueueTopics, ForumContext.IsSuperMod || _mod.QueuePosts);

                        break;



                    case ModerateCommandType.Pin:

                        _expires = DateTime.TryParse(form["expires"], out _dateTime) ? _dateTime.ToUtcDateTime() : (DateTime?)null;

                        TopicRepo.Mod_ToggleSticky(_ids, (short)PriorityType.Sticky, _expires);

                        break;

                    case ModerateCommandType.UnPin:
                        TopicRepo.Mod_ToggleSticky(_ids, (short)PriorityType.Normal, null);
                        break;

                    case ModerateCommandType.Lock:

                        TopicRepo.Mod_ToggleLock(_ids, true);
                        break;

                    case ModerateCommandType.UnLock:
                        TopicRepo.Mod_ToggleLock(_ids, false);
                        break;

                    case ModerateCommandType.Del:
                        TopicRepo.Mod_Delete(_ids, _fid, ForumContext.IsSuperMod || _mod.DeleteTopics, ForumContext.IsSuperMod || _mod.DeletePosts);

                        break;

                    case ModerateCommandType.Move:

                        int _moveTo = int.Parse(form["moveTo"]);
                        bool _allowRedirect = Convert.ToBoolean(form["enabledRedirect"]);

                        _expires = DateTime.TryParse(form["expires"], out _dateTime) ? _dateTime.ToUtcDateTime() : (DateTime?)null;
                     
                        TopicRepo.Mod_MoveToForum(_ids, _moveTo, _allowRedirect, _expires);

                        break;

                    case ModerateCommandType.UnMove:
                        TopicRepo.Mod_UnMove(_ids);
                        break;


                }
            }
            else
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.ModerateAccessDenied);
            }

            _msg.ReturnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.FIND_FORUM, _fid);

            return JavaScript(_msg.ToJavaScript());
        }

        #endregion


        #region Report

        public ActionResult Report()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Report(FormCollection form)
        {

            int _id = int.Parse(Request["Id"]);
            var _msg = Msg.Create();

            if (ForumContext.Logined || ForumContext.Configuration.AllowGuestReport)
            {

                string _from = ForumContext.Logined ? ForumContext.UserInfo.UserName : ForumContext.ClientIp;

                int _userId = ForumContext.Logined ? ForumContext.UserInfo.UserId : 0;

                string _reason = form["Reason"];

                var t = TopicRepo.Detail(_id);

                if (ForumContext.Configuration.WhenReportSendAdminEmail)
                {
                    var _subject = ForumContext.GetText(LanguageSection.REPORT, "EMAIL_SUBJECT");

                    var _body = string.Format(ForumContext.GetText(LanguageSection.REPORT, "EMAIL_BODY"), _from,
                                              ForumContext.GetAbsoluteUrl(ForumUrls.FIND_POST, t.TopicId),
                                              t.TopicName, _reason);

                    EmailQueueRepo.Save(ForumContext.Configuration.SmtpSender, ForumContext.Configuration.AdminEmail, _subject, _body, EmailPriority.Hight);

                }


                ReportRepo.Save(t.TopicId, _userId, ForumContext.ClientIp, _reason);

                _msg.Text = ForumContext.GetText(LanguageSection.REPORT, "SEND_COMPLETE");
            }

            return Json(_msg);
        }

        #endregion


        #region Post


        public ActionResult EditPost()
        {

            ViewBag.Command = CommandType.Edit;
            return NewPost();
        }


        public ActionResult NewPoll()
        {

            ViewBag.Command = CommandType.NewPoll;

            /*return NewPost();*/
            return View();
        }

        public ActionResult ReplyPoll()
        {
            ViewBag.Command = CommandType.ReplyPoll;
            return NewPost();
        }

        public ActionResult NewReply()
        {

            ViewBag.Command = CommandType.Reply;
            return NewPost();
        }

        public ActionResult AddPost()
        {

            ViewBag.Command = CommandType.NewPost;
            return NewPost();

        }

        [ValidateAuthentication]
        public ActionResult NewPost()
        {

            var _cmd = ViewBag.Command ?? CommandType.NewPost;

            int _id = int.Parse(Request.QueryString["Id"]);

            bool _accessDenied = false;
            var _buttonText = string.Empty;

            Topic _t = null;

            Forum _f = null;

            ForumUrl _url = null;

            switch ((CommandType)_cmd)
            {
                case CommandType.ReplyPoll:
                case CommandType.Reply:

                    _t = TopicRepo.Info(_id);

                    var _quote = new StringBuilder();

                    var _quoteCookie = Request.Cookies.Get("mvcforum_quote");

                    var _isQuote = Request.QueryString["quote"] == "1";

                    if (_quoteCookie != null && !string.IsNullOrWhiteSpace(_quoteCookie.Value))
                    {

                        var _posts = _quoteCookie.Value.Replace('|', ';');

                        var topics = TopicRepo.List(_t.ReplyTo.HasValue ? _t.ReplyTo.Value : _t.TopicId, _posts);

                        foreach (Topic topic in topics)
                        {
                            _quote.AppendFormat("[QUOTE={0};{1}]<p>{2}</p>[/QUOTE]<br /><br />", topic.UserName, topic.TopicId, topic.Message);
                        }

                        if (_isQuote)
                        {
                            _quote.AppendFormat("[QUOTE={0};{1}]<p>{2}</p>[/QUOTE]<br /><br />", _t.UserName, _t.TopicId, _t.Message);
                        }


                    }
                    if (_isQuote)
                    {
                        _quote.AppendFormat("[QUOTE={0};{1}]<p>{2}</p>[/QUOTE]<br /><br />", _t.UserName, _t.TopicId, _t.Message);
                    }

                    _t.Message = _quote.Length > 0 ? _quote.ToString() : string.Empty;

                    //  _t.TopicName = string.Empty;

                    _url = new ForumUrl
                               {
                                   Title =
                                       string.Format("{0} {1}", ForumContext.GetText(LanguageSection.POST, "Reply"),
                                                     _t.TopicName)
                               };

                    _buttonText = ForumContext.GetText(LanguageSection.POST, "Save");

                    _f = ForumRepo.Info(_t.ForumId);

                    _accessDenied = !(ForumContext.AllowAccess(_cmd, _f, _t));


                    break;

                case CommandType.Edit:

                    _buttonText = ForumContext.GetText(LanguageSection.POST, "Update");

                    _t = TopicRepo.Info(_id);

                    _url = new ForumUrl
                    {
                        Title =
                            string.Format("{0} {1}", ForumContext.GetText(LanguageSection.POST, "Edit"),
                                          _t.TopicName)
                    };

                    if (_t.PriorityExpires.HasValue)
                        _t.PriorityExpires = _t.PriorityExpires.Value.ToUserTimeZoneDateTime();

                    _accessDenied = !ForumContext.AllowAccess(CommandType.Edit, null, _t);

                    break;

                case CommandType.NewPoll:

                   

                    _f = ForumRepo.Info(_id);

                    _accessDenied = !(ForumContext.AllowAccess(CommandType.NewPoll, _f, null));//!(_f != null && ForumContext.AllowNewPolls(_f.AllowRoles));

                    _url = new ForumUrl
                    {
                        Title = ForumContext.GetText(LanguageSection.POST, "NEW_POLL")
                    };

                    _buttonText = ForumContext.GetText(LanguageSection.POST, "Save");


                    break;

                default:

                    _url = new ForumUrl
                    {
                        Title = ForumContext.GetText(LanguageSection.POST, "PAGE_NAME")
                    };


                    _f = ForumRepo.Info(_id);

                    _accessDenied = !(ForumContext.AllowAccess(CommandType.NewPost, _f, null));

                    _buttonText = ForumContext.GetText(LanguageSection.POST, "Save");

                    break;

            }


            List<ForumUrl> _navAddress = ForumRepo.BuildForumUrls(_t != null ? _t.ForumId : _id);

            _navAddress.Add(_url);

            ViewBag.NavAddress = _navAddress;
            ViewBag.ActiveUrl = _url;


            if (_accessDenied)
            {
                ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.AccessDenied);
                ViewBag.ShowLogin = true;
                return View("Message");
            }



            var _isMod = ForumContext.IsModerated(_t != null ? _t.ForumId : _id);


            #region Priority

            var _allowPriority = ForumContext.AllowStickyPosts;

            if (_allowPriority)
            {
                /*var _priorityTypes = new List<SelectListItem>();

                var _priorityEnums = Enum.GetValues(typeof(PriorityType));

                foreach (int val in _priorityEnums)
                {
                    _priorityTypes.Add(new SelectListItem()
                    {
                        Value = val.ToString(),
                        Text = ForumContext.GetText(LanguageSection.POST, "PRIORITY_" + Enum.GetName(typeof(PriorityType), val)),
                        Selected = _t != null && val == _t.Priority
                    });
                }*/

                #region YesNo


                ViewBag.PriorityTypes = new List<SelectItem>
                                {
                                    new SelectItem
                                        {
                                            Text = "Yes",
                                            Value = ((int)PriorityType.Sticky).ToString(),
                                            CssClass = "radio-yes"
                                        },
                                    new SelectItem
                                        {
                                            Text = "No",
                                            Value = "0",
                                            CssClass = "radio-no"
                                        }
                                };

                #endregion



            }


            ViewBag.AllowPriority = _allowPriority;


            #endregion


            #region Notify Type

            var _notifies = Enum.GetValues(typeof(NotificationType));

            var _notifyType = (from int val in _notifies
                               select new SelectListItem
                               {
                                   Text = ForumContext.GetText(LanguageSection.SUBSCRIPTION, Enum.GetName(typeof(NotificationType), val)),
                                   Value = val.ToString(),
                                   Selected = val == (int)NotificationType.UnSubcribe
                               }).ToList();

            ViewBag.NotifyType = _notifyType;
            #endregion


            ViewBag.Smiles = SmileRepo.List();

            ViewBag.IsMod = _isMod;



            ViewBag.Cmd = ForumContext.Encrypt((int)(CommandType)_cmd, _t == null || _cmd == CommandType.Edit ? _id : _t.ReplyTo > 0 ? _t.ReplyTo : _t.TopicId);

            ViewBag.CommandType = _cmd;

            ViewBag.ButtonText = _buttonText;

            return View("NewPost", _t);
        }


        [HttpPost]
        [ValidatePostback]
        [ValidateAuthentication]
        [ValidateAntiForgeryToken]
        [ValidateAntiModelInjection("cmd")]
        [ValidateInput(false)]
        public ActionResult NewPost(FormCollection form)
        {
            var _msg = Msg.Create();

            var _htmlText = form["message"] ?? form["msg"];

            var _word = _htmlText.HtmlToPlainText();

            if (!string.IsNullOrWhiteSpace(_word) && (ForumContext.Configuration.RequiredPostLength <= 0 || _word.Length > ForumContext.Configuration.RequiredPostLength))
            {

                try
                {




                    var _post = new Topic
                                    {
                                        IsApproved = true

                                    };

                    Topic t = null;
                    int Id;
                    var _quote = new StringBuilder();

                    var _quoteCookie = Request.Cookies.Get("mvcforum_quote");

                    string[] _params = ForumContext.Decrypt(form["cmd"]);

                    var _cmd = (CommandType)int.Parse(_params[0]);

                    int _id = int.Parse(_params[1]);

                    switch (_cmd)
                    {

                        case CommandType.NewPoll:
                            break;
                        case CommandType.NewPost:
                            break;

                        case CommandType.Reply:

                            t = TopicRepo.Info(_id);

                            _post.ReplyTo = _id;

                            bool _isQuoteInclude = false;
                            bool.TryParse(form["quote_include"], out _isQuoteInclude);
                            if (_isQuoteInclude)
                            {
                                if (_quoteCookie != null && !string.IsNullOrWhiteSpace(_quoteCookie.Value))
                                {

                                    var topics = TopicRepo.List(_id, _quoteCookie.Value.Replace('|', ';'));

                                    foreach (Topic topic in topics)
                                    {

                                        _quote.AppendFormat("[QUOTE={0};{1}]<p>{2}</p>[/QUOTE]<br /><br />", topic.UserName, topic.TopicId, topic.Message);

                                    }

                                }
                            }

                            break;

                        case CommandType.Edit:

                            t = TopicRepo.Info(_id);

                            // 0: Add new Post: >0 Edit post
                            _post.TopicId = _id;


                            break;
                    }

                    // forum detail
                    Forum f = ForumRepo.Detail(t != null ? t.ForumId : _id);

                    _post.ForumId = f.ForumId;


                    #region Check Access

                    if (!ForumContext.AllowAccess(_cmd, f, t))
                    {
                        _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.PostAccessDenied);
                        return Json(_msg);
                    }

                    #endregion


                    #region Check Approved


                    var _moderateType = (ModerateType)f.ModerateType;

                    if (_moderateType != ModerateType.None)
                    {
                        _post.IsApproved = ForumContext.IsSuperMod ||
                                           ForumContext.UserInfo.Permissions.AlwaysPostAprroved ||
                                           ForumContext.IsModerated(f.ForumId) ||
                                           (_moderateType == ModerateType.AllNewRepliesButNotTopics && _cmd == CommandType.Reply) ||
                                            (_moderateType == ModerateType.AllNewTopicsButNotReplies && (_cmd == CommandType.NewPost || _cmd == CommandType.NewPoll)) ||
                                            (_cmd == CommandType.Edit && ForumContext.UserInfo.Permissions.QueueEdited);
                    }


                    #endregion

                    short _priority;
                    DateTime _dateTimeout;

                    short.TryParse(form["priority"], out _priority);

                    DateTime.TryParse(form["date_expires"], out _dateTimeout);

                    // check sticky posts
                    if (_priority == (short)PriorityType.Sticky && (ForumContext.AllowStickyPosts))
                    {
                        _post.Priority = _priority;

                        var _expires = _dateTimeout.ToUtcDateTime();
                        if (_expires < DateTime.UtcNow)
                            _post.PriorityExpires = null;
                        else
                            _post.PriorityExpires = _expires;


                    }

                    _post.Message = (_quote + _htmlText).HtmlSanitize();

                    _post.Icon = form["Icon"];

                    _post.Tags = form["Tags"];

                    _post.TopicName = t != null && string.IsNullOrWhiteSpace(form["topicName"]) ? null : form["topicName"];

                    _post.RemoteUrl = form["remoteUrl"];

                    _post.IP = ForumContext.ClientIp;

                    _post.UserId = ForumContext.UserInfo.UserId;

                    _post.UserName = ForumContext.UserInfo.UserName;

                    _post.IncreasePosts = f.IncreaseMemberPosts;

                    TopicRepo.Save(_post, out Id);

                    NotificationRepo.Save((short)_cmd, ForumContext.UserInfo.UserId, 0, _post.ForumId, _cmd == CommandType.NewPost || _cmd == CommandType.NewPoll ? -1 : Id, ForumContext.GetAbsoluteUrl(ForumUrls.FIND_POST, Id));


                    //return Json(_post);


                    _msg.ReturnUrl = _post.IsApproved ? ForumContext.GetAbsoluteUrl(ForumUrls.FIND_POST, Id) : ForumContext.GetAbsoluteUrl(ForumUrls.MEMBERS, "WaitApprovedFromModerator");

                    if (ForumContext.Configuration.WhenNewPostSendAdminEmail && !ForumContext.IsAdmin)
                    {

                        string _subject = string.Empty;


                        switch (_cmd)
                        {
                            case CommandType.Edit:
                                _subject = ForumContext.GetText(LanguageSection.TOPICS, "Edit");
                                break;
                            case CommandType.Reply:
                            case CommandType.ReplyPoll:
                                _subject = ForumContext.GetText(LanguageSection.TOPICS, "RE");
                                break;
                        }

                        _subject = string.Format("{0}-{1}", _subject, !string.IsNullOrWhiteSpace(_post.TopicName) ? _post.TopicName : t != null ? t.TopicName : string.Empty);


                        EmailQueueRepo.Save(ForumContext.Configuration.SmtpSender,
                            ForumContext.Configuration.AdminEmail, _subject, string.Format("{0} <br /><br />-----------------------<br />{1}", _post.Message, ForumContext.GetAbsoluteUrl(ForumUrls.FIND_POST, Id)), EmailPriority.Normal);
                    }


                    // remove quote cookie

                    if (_quoteCookie != null)
                    {
                        _quoteCookie.Expires = DateTime.Now.AddDays(-360);

                        Response.AppendCookie(_quoteCookie);
                    }

                }
                catch (Exception ex)
                {
                    EmailQueueRepo.Save(ForumContext.Configuration.SmtpSender, ForumContext.Configuration.AdminEmail, "System Exception", ex.ToString(), EmailPriority.Hight);

                }



            }
            else
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "ShortLength");
            }


            return JavaScript(_msg.ToJavaScript());

        }


        #endregion

        #region Forum Message

        public ActionResult Message(string id)
        {

            var _url = new ForumUrl
                           {
                               Title = ForumContext.GetText(LanguageSection.MESSAGES, "PAGE_NAME"),
                           };

            var _add = new List<ForumUrl> { _url };

            ViewBag.NavAddress = _add;

            ViewBag.ActiveUrl = _url;

            var _msg = ForumContext.GetText(LanguageSection.MESSAGES, id);

            if (string.IsNullOrWhiteSpace(_msg))
            {
                _msg = ForumContext.GetText(LanguageSection.MESSAGES, "UnknownError");
            }

            ViewBag.Message = _msg;

            return View();
        }

        #endregion

        #region SiteMap & Rss Feed

        public ActionResult Feed(int? id)
        {

            Response.ContentType = "application/rss+xml";

            Forum _f = null;

            if (id.HasValue && id > 0)
            {
                _f = ForumRepo.Info(id.Value);

                if (!ForumContext.ForumAllowRoles(_f.AllowRoles))
                {
                    return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.MEMBERS, Messages.AccessDenied));
                }
            }

            ViewBag.Forum = _f;

            var _pageSize = ForumContext.Configuration.FeedPageSize;

            var _items = TopicRepo.Feed(_f != null ? _f.ForumId : 0, _pageSize);

            return PartialView("Feed", _items);
        }


        public ActionResult Sitemap(int? page)
        {

            int _pageIndex = 1;
            if (page.HasValue && page.Value > 1)
                _pageIndex = page.Value;

            var _pageSize = ForumContext.Configuration.SiteMapPageSize;

            var _topics = TopicRepo.SearchEngineSitemap(_pageIndex, _pageSize);

            if (_topics.Count > 0)
            {
                XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";

                var _sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                    new XElement(ns + "urlset",
                          new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"),
                            new XAttribute(XNamespace.Xmlns + "geo", "http://www.google.com/geo/schemas/sitemap/1.0"),


                        _topics.Select(x =>
                          new XElement("url",
                          new XElement("loc", ForumContext.ThreadLink(x.TopicId, x.TopicName)),
                          new XElement("lastmod", x.LastPosted.ToString("yyyy-MM-ddTHH:mm:sszzz")),
                          new XElement("changefreq", "always"),
                          new XElement("priority", "0.8")
                          ))

                        ));
                return Content(_sitemap.ToString(), "text/xml", Encoding.UTF8);
            }

            return Content("");
        }

        #endregion


        #region Redirect

        /*  public ActionResult Redirect()
        {
            var _url = Request.QueryString["url"];
            if(!string.IsNullOrWhiteSpace(_url))
            {
                
            }
        }*/
        #endregion



    }
}
